<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - MSSQL to MySQL</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 1.8rem;
        }

        .header-actions {
            display: flex;
            gap: 15px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-block;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 30px 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-card h3 {
            color: #2c3e50;
            font-size: 2rem;
            margin-bottom: 10px;
        }

        .stat-card p {
            color: #6c757d;
            font-weight: 600;
        }

        .databases-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .section-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #dee2e6;
        }

        .section-header h2 {
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .section-header p {
            color: #6c757d;
        }

        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }

        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-running {
            background: #fff3cd;
            color: #856404;
        }

        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }

        .status-pending {
            background: #cce7ff;
            color: #004085;
        }

        .view-logs-btn, .btn-view {
            background: #17a2b8;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            margin-right: 5px;
        }

        .view-logs-btn:hover, .btn-view:hover {
            background: #138496;
        }

        .btn-delete {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            margin-right: 5px;
        }

        .btn-delete:hover {
            background: #c82333;
        }

        .batch-actions {
            padding: 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .btn-batch-delete {
            background: #dc3545;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
        }

        .btn-batch-delete:hover {
            background: #c82333;
        }

        .btn-batch-delete:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
        }

        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 10px;
            width: 90%;
            max-width: 800px;
            max-height: 80vh;
            overflow: hidden;
        }

        .modal-header {
            background: #2c3e50;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
        }

        .close {
            color: white;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            opacity: 0.7;
        }

        .modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        /* 进度条样式 */
        .progress-section {
            margin-bottom: 16px;
        }
        .progress-bar {
            width: 100%;
            height: 12px;
            background: #e9ecef;
            border-radius: 6px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.4s ease;
        }
        .progress-info {
            display: flex;
            gap: 16px;
            margin-top: 8px;
            color: #495057;
            font-size: 0.92rem;
        }

        .log-entry {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border-left: 4px solid #dee2e6;
        }

        .log-entry.running {
            background: #fff3cd;
            border-left-color: #ffc107;
        }

        .log-entry.completed {
            background: #d4edda;
            border-left-color: #28a745;
        }

        .log-entry.failed {
            background: #f8d7da;
            border-left-color: #dc3545;
        }

        .log-time {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 5px;
        }

        .log-message {
            font-weight: 600;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .empty-state svg {
            width: 64px;
            height: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                gap: 15px;
            }

            .header-actions {
                width: 100%;
                justify-content: center;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .modal-content {
                width: 95%;
                margin: 10% auto;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>管理后台</h1>
            <div class="header-actions">
                <a href="/" class="btn btn-primary">返回主页</a>
                <a href="/admin/logout" class="btn btn-secondary">退出登录</a>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="stats-grid">
            <div class="stat-card">
                <h3 id="totalMigrations">0</h3>
                <p>总迁移次数</p>
            </div>
            <div class="stat-card">
                <h3 id="successfulMigrations">0</h3>
                <p>成功迁移</p>
            </div>
            <div class="stat-card">
                <h3 id="failedMigrations">0</h3>
                <p>失败迁移</p>
            </div>
            <div class="stat-card">
                <h3 id="runningMigrations">0</h3>
                <p>正在进行</p>
            </div>
        </div>

        <div class="databases-section">
            <div class="section-header">
                <h2>数据库迁移记录</h2>
                <p>查看所有MSSQL数据库迁移的历史记录</p>
            </div>
            <div class="batch-actions">
                <button class="btn-batch-delete" id="batchDeleteBtn" onclick="batchDelete()" disabled>
                    批量删除选中项
                </button>
                <span id="selectedCount">已选择 0 项</span>
            </div>
            <div class="table-container" id="databasesTable">
                <!-- 数据表格将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>

    <!-- 日志查看模态框 -->
    <div id="logsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>迁移日志</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <div id="progressSection" class="progress-section">
                    <div class="progress-bar">
                        <div id="progressFill" class="progress-fill"></div>
                    </div>
                    <div class="progress-info">
                        <span id="progressText">进度：0%</span>
                        <span id="progressCount">已迁移 0/0</span>
                        <span id="progressETA">剩余时间：计算中</span>
                    </div>
                </div>
                <div id="logsContent">
                    <!-- 日志内容将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        let databases = [];

        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadDatabases();
            
            // 设置定时刷新
            setInterval(loadDatabases, 30000); // 每30秒刷新一次
        });

        async function loadDatabases() {
            try {
                const response = await fetch('/api/admin/databases');
                databases = await response.json();
                
                updateStats();
                renderDatabasesTable();
            } catch (error) {
                console.error('加载数据失败:', error);
            }
        }

        function updateStats() {
            const total = databases.length;
            const successful = databases.filter(db => db.last_status === 'completed').length;
            const failed = databases.filter(db => db.last_status === 'failed').length;
            const running = databases.filter(db => db.last_status === 'running').length;

            document.getElementById('totalMigrations').textContent = total;
            document.getElementById('successfulMigrations').textContent = successful;
            document.getElementById('failedMigrations').textContent = failed;
            document.getElementById('runningMigrations').textContent = running;
        }

        function renderDatabasesTable() {
            const container = document.getElementById('databasesTable');
            
            if (databases.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12,3C7.58,3 4,4.79 4,7C4,9.21 7.58,11 12,11C16.42,11 20,9.21 20,7C20,4.79 16.42,3 12,3M4,9V12C4,14.21 7.58,16 12,16C16.42,16 20,14.21 20,12V9C20,11.21 16.42,13 12,13C7.58,13 4,11.21 4,9M4,14V17C4,19.21 7.58,21 12,21C16.42,21 20,19.21 20,17V14C20,16.21 16.42,18 12,18C7.58,18 4,16.21 4,14Z"/>
                        </svg>
                        <h3>暂无迁移记录</h3>
                        <p>还没有进行过数据库迁移操作</p>
                    </div>
                `;
                return;
            }

            const tableHTML = `
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>
                                <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                            </th>
                            <th>MSSQL数据库</th>
                            <th>MySQL数据库</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>日志数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${databases.map(db => `
                            <tr>
                                <td>${db.id}</td>
                                <td>
                                    <input type="checkbox" class="record-checkbox" value="${db.id}">
                                </td>
                                <td>
                                    <strong>${db.mssql_database}</strong><br>
                                    <small>${db.mssql_host}:${db.mssql_port}</small>
                                </td>
                                <td>
                                    <strong>${db.mysql_database}</strong><br>
                                    <small>${db.mysql_host}:${db.mysql_port}</small>
                                </td>
                                <td>
                                    <span class="status-badge status-${db.last_status || 'pending'}">
                                        ${getStatusText(db.last_status || 'pending')}
                                    </span>
                                </td>
                                <td>${formatDate(db.created_at)}</td>
                                <td>${db.log_count}</td>
                                <td>
                                    <button class="btn-view" onclick="viewLogs(${db.id})">查看日志</button>
                                    <button class="btn-delete" onclick="deleteSingle(${db.id})">删除</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
            
            container.innerHTML = tableHTML;
            
            // 为复选框添加事件监听器
            document.querySelectorAll('.record-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateBatchDeleteButton);
            });
        }

        function getStatusText(status) {
            const statusMap = {
                'completed': '已完成',
                'running': '进行中',
                'failed': '失败',
                'pending': '等待中'
            };
            return statusMap[status] || '未知';
        }

        function formatDateTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 全选/取消全选功能
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.record-checkbox');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            
            updateBatchDeleteButton();
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkboxes = document.querySelectorAll('.record-checkbox:checked');
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            const selectedCount = document.getElementById('selectedCount');
            
            batchDeleteBtn.disabled = checkboxes.length === 0;
            selectedCount.textContent = `已选择 ${checkboxes.length} 项`;
        }

        // 单个删除
        async function deleteSingle(configId) {
            if (!confirm('确定要删除这条迁移记录吗？删除后将无法恢复。')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/admin/delete_migration/${configId}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('删除成功');
                    loadDatabases(); // 重新加载数据
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 批量删除
        async function batchDelete() {
            const checkboxes = document.querySelectorAll('.record-checkbox:checked');
            const configIds = Array.from(checkboxes).map(cb => parseInt(cb.value));
            
            if (configIds.length === 0) {
                alert('请选择要删除的记录');
                return;
            }
            
            if (!confirm(`确定要删除选中的 ${configIds.length} 条记录吗？删除后将无法恢复。`)) {
                return;
            }
            
            try {
                const response = await fetch('/api/admin/delete_migrations', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ config_ids: configIds })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert(result.message);
                    loadDatabases(); // 重新加载数据
                    document.getElementById('selectAll').checked = false;
                    updateBatchDeleteButton();
                } else {
                    alert('批量删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('批量删除失败:', error);
                alert('批量删除失败: ' + error.message);
            }
        }

        async function viewLogs(configId) {
            try {
                await fetchAndRenderLogs(configId);
                pollProgress(configId);
                const modal = document.getElementById('logsModal');
                modal.style.display = 'block';
            } catch (error) {
                console.error('加载日志失败:', error);
                alert('加载日志失败');
            }
        }

        async function fetchAndRenderLogs(configId) {
            const response = await fetch(`/api/admin/logs/${configId}`);
            const logs = await response.json();
            const content = document.getElementById('logsContent');
            if (logs.length === 0) {
                content.innerHTML = `
                    <div class="empty-state">
                        <p>暂无日志记录</p>
                    </div>
                `;
            } else {
                content.innerHTML = logs.map(log => `
                    <div class="log-entry ${log.status}">
                        <div class="log-time">${formatDateTime(log.created_at)}</div>
                        <div class="log-message">${log.message}</div>
                    </div>
                `).join('');
            }
        }

        function pollProgress(configId) {
            clearInterval(window._progressTimer);
            clearInterval(window._logsTimer);
            window._progressTimer = setInterval(async () => {
                try {
                    const resp = await fetch(`/api/admin/progress/${configId}`);
                    const info = await resp.json();
                    if (!info || info.status === 'unknown') return;
                    const percent = info.percent || 0;
                    document.getElementById('progressFill').style.width = `${percent}%`;
                    document.getElementById('progressText').textContent = `进度：${percent}%`;
                    document.getElementById('progressCount').textContent = `已迁移 ${info.done || 0}/${info.total || 0}`;
                    document.getElementById('progressETA').textContent = info.eta_seconds != null ? `剩余时间：~${Math.ceil(info.eta_seconds)}秒` : '剩余时间：计算中';

                    if (info.status === 'completed' || info.status === 'failed') {
                        clearInterval(window._progressTimer);
                        clearInterval(window._logsTimer);
                        loadDatabases();
                    }
                } catch (e) {
                    console.warn('进度查询失败', e);
                }
            }, 2000);

            // 同步刷新日志
            window._logsTimer = setInterval(() => fetchAndRenderLogs(configId), 3000);
        }

        // 模态框控制
        document.querySelector('.close').addEventListener('click', function() {
            document.getElementById('logsModal').style.display = 'none';
            clearInterval(window._progressTimer);
            clearInterval(window._logsTimer);
        });

        window.addEventListener('click', function(event) {
            const modal = document.getElementById('logsModal');
            if (event.target === modal) {
                modal.style.display = 'none';
                clearInterval(window._progressTimer);
                clearInterval(window._logsTimer);
            }
        });
    </script>
</body>
</html>